package org.huangrui.spark.java.core.rdd.operate;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import java.util.Arrays;
import java.util.List;

/**
 * @Author hr
 * @Create 2024-10-17 3:46
 */
public class Spark05_Operate_Transform_groupBy_1 {
    public static void main(String[] args) {
        final SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("spark");
        final JavaSparkContext jsc = new JavaSparkContext(conf);
        List<Integer> nums = Arrays.asList(1, 2, 3, 4);
        JavaRDD<Integer> rdd = jsc.parallelize(nums, 2);
        // TODO RDD的方法：groupBy,按照指定的规则对数据进行分组
        // 1 -> 奇数
        // 2 -> 偶数
        // 3 -> 奇数
        // 4 -> 偶数
        // (偶数, [2,4])
        // (奇数, [1,3])
        /*JavaPairRDD<Object, Iterable<Integer>> pairRdd = rdd.groupBy(new Function<Integer, Object>() {
            @Override
            public Object call(Integer v1) throws Exception {
                return v1 % 2 == 0 ? "偶数" : "奇数";
            }
        });*/
        JavaPairRDD<String, Iterable<Integer>> pairRdd = rdd.groupBy(v1 -> v1 % 2 == 0 ? "偶数" : "奇数");

        pairRdd.collect().forEach(System.out::println);

        jsc.close();
    }
}
